<?php

namespace Boosen\Admin\EmailAlert\Controllers;


use App\Http\Controllers\Controller;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Widgets\Form;

use Boosen\Admin\EmailAlert\Models\EmailTemplate;

use Boosen\Admin\EmailAlert\Lib\Template;
use App\Lib\EmailAlert\Template as TemplateB;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Input;

use App\Models\Journal;
use Mail,Config;
/**
 * 
 */
class EmailSendingController extends Controller
{
	use ModelForm;

	public function show(Request $request)
	{
		Admin::script($this->script($request));
		return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');
            
            $content->body($this->form()->render());
        });
	}


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {

		$form = new Form();

		$form->action(route('email.send'));

		$form->textarea('emails', 'Emails')->placeholder('a@test.com
b@test.com
...')->attribute('required', 'required')->rules('required');

		$templates = EmailTemplate::get();

		$tNew = [];
		foreach ($templates as $template) {
			$tNew[$template->id] = $template->name;
		}


		$default = Template::getTemplates();
        $defaultB = TemplateB::getTemplates();

        $default = array_merge($default, $defaultB);

		$form->select('template', 'Template')->options($default + $tNew)->attribute('required', 'required')->rules('required');
		$form->text('subject', 'Subject')->attribute('required', 'required')->rules('required');

		// $newIssue = new NewIssuePublishTemplate();
		$form->ueditor('body', 'Body')->attribute('required', 'required')->rules('required');

		return $form;
    }

    public function send(Request $request)
    {
    	$data = Input::all();
    	$form = $this->form();
    	if ($validationMessages = $form->validationMessages($data)) {
            return back()->withInput()->withErrors($validationMessages);
        }

        $journal = Journal::currentJournal();

        $transport = (new \Swift_SmtpTransport($journal->email, $journal->port))
           ->setUsername($journal->email_name)
           ->setPassword($journal->email_password)
           ->setEncryption($journal->smtp);

        Mail::setSwiftMailer(new \Swift_Mailer($transport));

    	$num = Mail::send([], [], function($message) use ($data, $journal) {
            $message->from($journal->email_name);
            $message->subject($data['subject']);
    		$message->setBody($data['body'], 'text/html');

        	$emails = explode("\r\n", $data['emails']);
    		foreach ($emails as $email) {
    			$message->to(trim($email));
    		}
    	});
    	$request->session()->flash('status', 'done.');
    	return redirect(route('email.show'));
    }

    public function template(Request $request)
    {
    	$id = $request->input('id');
    	$tArr = [
    		'subject' => '',
    		'body' => ''
    	];
    	if (isInteger($id)) {
    		$template = EmailTemplate::find($id);

    		$tArr['subject'] = $template->subject;
    		$tArr['body'] = $template->body;
    	} else {
    		$klassName = '\\App\\Lib\\EmailAlert\\' . $id . 'Template';
    		if (class_exists($klassName)) {
    			$klass = new $klassName();
    			if ($klass instanceOf Template) {
	    			$tArr['subject'] = $klass->subject();
		    		$tArr['body'] = $klass->body();
		    	}
    		} else {
    			$klassName = '\\Boosen\\Admin\\EmailAlert\\Lib\\' . $id . 'Template';
    			
	    		if (class_exists($klassName)) {
	    			$klass = new $klassName();
	    			if ($klass instanceOf Template) {
		    			$tArr['subject'] = $klass->subject();
		    			$tArr['body'] = $klass->body();
		    		}
	    		}
    		}
    	}

    	return response()->json($tArr);
    }

    private function script($request)
    {
    	$url = route('email.template');
    	$toastr = '';
    	if ($request->session()->has('status')) {
			$toastr = 'toastr.success("发送成功");';
		}

    	return <<<EOT
{$toastr}
$('select[name="template"]').change(function() {
	var template_id = $(this).val();
	if (template_id == '') {
		return ;
	}
$.get('{$url}', {id: template_id}, function(res) {
		$('#subject').val(res.subject);
		ue.setContent(res.body);
	});
});
EOT;
    }
}